<?php

/**
 * Erra_Fields_Search_MultiCheckBox - Multicheckbox search object
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
class Erra_Fields_Search_MultiCheckBox extends Erra_Fields_Base_Field {
    protected $_operator;

    public function __construct($objectId) {
        parent::__construct($objectId);
        $this->setDatabaseType('none');
    }

    /**
     * Edits multi checkbox search instance
     *
     * @param mixed $lang
     * @return
     */
    public function editInstance(Array $extraProperties=null) {
        $res = '<div class="erra-form-field-instance">';
        $res .= $this->outputFieldHeader();
        
        
        $values = $this->getValue();
        $counter = 0;
        foreach ($this->fieldData as $checkboxKey => $checkboxValue) {
            $checked = (in_array($checkboxKey, $values)) ? ' checked ' : ' ';
            $res .= '<input '.$this->getHtmlAttributes($extraProperties).' type="checkbox" ' . $checked . 'name="' . $this->getHtmlName() . '[criteria][]" id="' . $this->getHtmlId() . '_criteria_' . $counter . '" value="' . $checkboxKey . '">' . $checkboxValue . ' ';
            $counter++;
        }
        $res .= '<input type="hidden" name="' . $this->getHtmlName() . '[operator]" id="' . $this->getHtmlId() . '_operator" value="' . $this->getOperator() . '"/>';
        $res .= '</div>';

        return $res;
    }

    function toHtml($displayParameters = null) {
        if (isset($this->fieldData) && is_array($this->fieldData) && isset($this->fieldData[$this->getRawData()])) {
            return $this->fieldData[$this->getRawData()];
        }
        return $this->getRawData();
    }

    /** Getters and setters */
    public function getValue() {
        $data = $this->getRawData();
        if (is_string($data)) {
            if (strstr($data, '§') !== false) {
                return explode('§', $data);
            } else {
                return array($data);
            }
        }
        return array();
    }

    public function setRawData($value) {
        // Values from $_POST
        if (is_array($value)) {
            $this->_rawData = implode('§', $value);
            // Values from elsewhere
        } else {
            $this->_rawData = $value;
        }
    }

    public function setOperator($operator) {
        $this->_operator = $operator;
        return $this;
    }

    public function getOperator() {
        return $this->_operator;
    }

}